#!/usr/bin/env python3
# -*- coding: utf-8 -*-

#  Copyright (C) 2020 ShenZhen Powersmart Information Technology Co.,Ltd
#  All Rights Reserved.
#  本软件为深圳博沃智慧开发研制。未经本公司正式书面同意，其他任何个人、团体不得使用、
#  复制、修改或发布本软件.

# @Time : 2025/9/10 09:19
# @File : llm_analysis_services.py
# @Project: 
# @Author : wanghongtao
# @Software: PyCharm
import time
import json
from dataclasses import dataclass
from typing import Dict, Any, Optional, List

from requests import Session
from sqlalchemy.orm import selectinload

from models import RegionalAnalysisResult
from models.service_class import ServiceClass, ServiceInstance
from models.prompt_template import PromptTemplate, PromptParameter
from services.ai_service_factory import AIService, ServiceConfig, ServiceRequest, ServiceResponse, ServiceType, \
    ServiceStatus
from models.analysis_task import TaskType
from services.ai_service_factory import AIService, ServiceConfig, ServiceRequest, ServiceResponse, ServiceType
from services.llm_service import llm_service_manager, LLMMessage, LLMService
from services.prompt_renderer import prompt_renderer
from services.ai_analysis_config_provider import config_provider, enhance_analysis_request_with_config
from core.config import settings
from core.logging_config import get_logger
from core.database import get_db_session, get_db
from core.service_config import ServiceParamsConfig
# 日志
logger = get_logger("llm_analysis_services")


@dataclass
class LLMAnalysisResult:
    """大模型分析结果"""
    analysis_type: str
    content: str
    structured_data: Dict[str, Any]
    confidence_score: float
    processing_time: float
    model_used: str
    token_usage: Dict[str, int]

llm_analysis_config = ServiceConfig(
    service_type=ServiceType.LLM_SERVICES,
    name="大模型分析基类",
    description="大模型分析服务基类",
    version="v1.0",
    enabled=True,
    max_concurrent_requests=10,
    timeout=30,
    retry_count=3,
    model_config={},
    api_config={}
)

class LLMAnalysisService(AIService):
    """大模型分析服务基类"""

    def __init__(self, config: ServiceConfig=llm_analysis_config):
        super().__init__(config)
        self.config = config


    def _get_system_prompt(self) -> str:
        """获取系统提示词"""
        raise NotImplementedError("子类必须实现此方法")

    async def initialize(self) -> bool:
        """初始化服务"""
        try:
            logger.info(f"初始化大模型分析服务: {self.analysis_type.value}")

            # 测试大模型连接
            health_check = await llm_service_manager.health_check()
            if not health_check["healthy"]:
                logger.error(f"大模型服务不可用: {health_check.get('error', 'Unknown error')}")
                return False

            logger.info(f"大模型分析服务初始化成功: {self.analysis_type.value}")
            return True

        except Exception as e:
            logger.error(f"大模型分析服务初始化失败: {str(e)}")
            return False

    async def process(self, request: ServiceRequest) -> ServiceResponse:
        """处理分析请求"""
        start_time = time.time()

        try:
            text = request.data.get("text", "")
            if not text:
                return ServiceResponse(
                    request_id=request.request_id,
                    service_type=request.service_type,
                    success=False,
                    error_message="文本内容不能为空"
                )

            # 使用大模型进行分析
            result = await self._analyze_with_llm(text, request.parameters)

            return ServiceResponse(
                request_id=request.request_id,
                service_type=request.service_type,
                success=True,
                data={
                    "analysis_result": result.__dict__,
                    "service_info": {
                        "analysis_type": self.analysis_type.value,
                        "provider": settings.llm_provider,
                        "model": settings.llm_model
                    }
                },
                processing_time=time.time() - start_time
            )

        except Exception as e:
            logger.error(f"大模型分析失败: {str(e)}")
            return ServiceResponse(
                request_id=request.request_id,
                service_type=request.service_type,
                success=False,
                error_message=str(e),
                processing_time=time.time() - start_time
            )

    async def _analyze_with_llm(self, text: str, parameters: Dict[str, Any]) -> LLMAnalysisResult:
        """使用大模型进行分析"""
        start_time = time.time()

        # 构建消息
        messages = [
            LLMMessage(role="system", content=self.system_prompt),
            LLMMessage(role="user", content=text)
        ]

        # 调用大模型
        response = await llm_service_manager.chat_completion(
            messages=messages,
            temperature=parameters.get("temperature", 0.3),
            max_tokens=parameters.get("max_tokens", 2000)
        )

        # 解析响应
        content = response.choices[0]["message"]["content"]
        structured_data = self._parse_response(content)

        return LLMAnalysisResult(
            analysis_type=self.analysis_type.value,
            content=content,
            structured_data=structured_data,
            processing_time=time.time() - start_time,
            model_used=response.model,
            token_usage=response.usage
        )

    def _parse_response(self, content: str) -> Dict[str, Any]:
        """解析大模型响应"""
        try:
            # 尝试解析JSON
            return json.loads(content)
        except json.JSONDecodeError:
            # 如果不是JSON，返回原始内容
            return {"raw_content": content}

    async def health_check(self) -> Dict[str, Any]:
        """健康检查"""
        try:
            llm_health = await llm_service_manager.health_check()

            return {
                "healthy": llm_health["healthy"],
                "service_type": "llm_analysis",
                "analysis_type": self.analysis_type.value,
                "provider": settings.llm_provider,
                "model": settings.llm_model,
                "llm_service_health": llm_health
            }
        except Exception as e:
            logger.error(f"大模型分析服务健康检查失败: {str(e)}")
            return {
                "healthy": False,
                "service_type": "llm_analysis",
                "error": str(e)
            }

    def get_capabilities(self) -> Dict[str, Any]:
        """获取服务能力"""
        return {
            "description": f"使用大模型进行{self.analysis_type.value}分析",
            "input_format": {"text": "string"},
            "output_format": {
                "analysis_result": "object",
                "structured_data": "object",
                "confidence_score": "float"
            },
            "supported_features": [
                "llm_analysis",
                "structured_output",
                "confidence_scoring"
            ]
        }

llm_run_config = ServiceConfig(
    service_type=ServiceType.LLM_SERVICES,
    name="大模型运行基类",
    description="大模型运行基类",
    version="v1.0")


class LLMRunService(AIService):
    """
    大模型运行服务
    
    功能：
    1. 获取ServiceClass类的数据
    2. 获取ServiceClass类对应的大模型参数、提示词类PromptTemplate
    3. 通过提示词类和传入的数据内容完成提示词的内容
    4. 依据大模型参数、提示词，调用LLM服务管理器使用智谱接口进行回答
    """
    
    def __init__(self, config: ServiceConfig=llm_run_config):
        super().__init__(config)
        self.service_type = ServiceType.AI_ANALYSIS
        self.llm_service_manager = llm_service_manager
        self.prompt_renderer = prompt_renderer

    async def run(self, service_class: ServiceClass, request_data: Dict[str, Any], db: Session) -> Dict[str, Any]:
        """
        运行大模型服务
        
        Args:
            service_class: 服务类对象
            request_data: 请求数据
            
        Returns:
            Dict[str, Any]: 大模型响应结果
        """
        try:
            # 1. 获取ServiceClass类的数据
            logger.info(f"开始执行服务: {service_class.name}")
            
            # 2. 获取ServiceClass类对应的大模型参数、提示词类PromptTemplate
            llm_params, prompt_template = self._get_service_config(service_class, db)
            
            # 3. 通过提示词类和传入的数据内容完成提示词的内容
            rendered_prompt = self._render_prompt(prompt_template, request_data)
            
            # 4. 依据大模型参数、提示词，调用LLM服务管理器使用智谱接口进行回答
            response = await self._call_llm_service(llm_params, rendered_prompt)
            
            logger.info(f"服务执行完成: {service_class.name}")
            return response
            
        except Exception as e:
            logger.error(f"服务执行失败: {service_class.name}, 错误: {str(e)}")
            raise
    
    def _get_service_config(self, service_class: ServiceClass, db:Session) -> tuple[Dict[str, Any], PromptTemplate]:
        """
        获取服务配置，包括LLM参数和提示词模板
        
        Args:
            service_class: 服务类对象
            
        Returns:
            tuple: (LLM参数, 提示词模板)
        """
        # 从服务类获取LLM配置
        llm_params = {
            "model": service_class.model_code,
            "provider": service_class.provider,
            "max_tokens": service_class.max_tokens,
            "temperature": service_class.temperature,
        }
        
        # 添加额外配置
        if service_class.config:
            llm_params.update(service_class.config)
        
        # 获取提示词模板
        prompt_template = self._get_prompt_template(service_class, db)
        
        logger.info(f"获取服务配置: 模型={llm_params['model']}, 提供商={llm_params['provider']}")
        return llm_params, prompt_template
    
    def _get_prompt_template(self, service_class: ServiceClass, db: Session) -> PromptTemplate:
        """
        获取服务类对应的提示词模板
        
        Args:
            service_class: 服务类对象
        Returns:
            PromptTemplate: 提示词模板对象
        """
        try:
            # 根据服务类型查找对应的提示词模板
            prompt_template = db.query(PromptTemplate).filter(
                PromptTemplate.id == service_class.prompt_template_id,
                PromptTemplate.is_active == True
            ).first()
            if not prompt_template:
                logger.warning(f"未找到服务名称为：{service_class.name}，"
                               f"服务分类：{service_class.category} 的提示词模板")

            return prompt_template
                
        except Exception as e:
            logger.error(f"获取提示词模板失败: {str(e)}")
            raise
    
    def _render_prompt(self, prompt_template: PromptTemplate, request_data: Dict[str, Any]) -> str:
        """
        渲染提示词内容
        
        Args:
            prompt_template: 提示词模板
            request_data: 请求数据
            
        Returns:
            str: 渲染后的提示词内容
        """
        try:
            # 构建参数定义
            parameter_definitions = []
            for param in prompt_template.parameters:
                param_def = {
                    'name': param.name,
                    'param_type': param.param_type,
                    'is_required': param.is_required,
                    'default_value': param.default_value
                }
                if param.description:
                    param_def['description'] = param.description
                parameter_definitions.append(param_def)
            
            # 使用提示词渲染引擎
            render_result = self.prompt_renderer.render(
                template_content=prompt_template.content,
                template_output_schema=prompt_template.output_schema,
                parameters=request_data,
                parameter_definitions=parameter_definitions
            )
            
            if render_result.validation_errors:
                logger.warning(f"提示词渲染验证错误: {render_result.validation_errors}")
            
            if render_result.missing_parameters:
                logger.warning(f"提示词渲染缺失参数: {render_result.missing_parameters}")
            
            rendered_prompt = render_result.rendered_prompt
            
            logger.info(f"提示词渲染完成，token数量: {render_result.token_count}")
            return rendered_prompt
            
        except Exception as e:
            logger.error(f"提示词渲染失败: {str(e)}")
            raise
    
    async def _call_llm_service(self, llm_params: Dict[str, Any], prompt: str) -> Dict[str, Any]:
        """
        调用LLM服务
        
        Args:
            llm_params: LLM参数配置
            prompt: 提示词内容
            
        Returns:
            Dict[str, Any]: LLM响应结果
        """
        try:
            # 构建LLM服务请求参数
            request_params = {
                "model": llm_params["model"],
                "temperature": llm_params.get("temperature", 0.1),
                "max_tokens": llm_params.get("max_tokens", 2000)
            }
            
            # 添加可选参数
            if "timeout" in llm_params:
                request_params["timeout"] = llm_params["timeout"]
            
            # 根据提供商选择服务
            provider = llm_params.get("provider", "zhipu")
            service_id = f"{provider}_{llm_params['model']}"
            messages = [
                LLMMessage(role="user", content=prompt)
            ]
            logger.info(f"LLM服务调用: {service_id}")
            response = await self.llm_service_manager.chat_completion(
                messages, provider,
                model=request_params.get("model"),
                max_tokens=request_params.get("max_tokens"),
                temperature=request_params.get("temperature", 0.1))

            # 处理响应
            result = {
                "success": True,
                "response": response,
                "model": llm_params["model"],
                "provider": provider,
                "prompt_length": len(prompt),
                "timestamp": response.processing_time
            }

            logger.info(f"LLM服务调用成功: {service_id}")
            return result
            
        except Exception as e:
            logger.error(f"LLM服务调用失败: {str(e)}")
            return {
                "success": False,
                "error": str(e),
                "model": llm_params.get("model", "unknown"),
                "provider": llm_params.get("provider", "unknown")
            }
    
    def get_service_info(self, service_class: ServiceClass) -> Dict[str, Any]:
        """
        获取服务信息
        Args:
            service_class: 服务类对象
        Returns:
            Dict[str, Any]: 服务信息
        """
        try:
            llm_params, prompt_template = self._get_service_config(service_class)
            
            return {
                "service_name": service_class.name,
                "service_type": service_class.service_id,
                "model_config": llm_params,
                "prompt_template": {
                    "name": prompt_template.name,
                    "description": prompt_template.description,
                    "parameter_count": len(prompt_template.parameters),
                    "enable_thinking": getattr(prompt_template, 'enable_thinking', False)
                },
                "status": "active" if service_class.is_active else "inactive"
            }
            
        except Exception as e:
            logger.error(f"获取服务信息失败: {str(e)}")
            return {"error": str(e)}


class ExtracInfoService(LLMRunService):
    """信息抽取服务 - 基于LLMRunService"""
    
    def __init__(self, config: ServiceConfig = None):
        # 使用信息抽取服务配置
        if config is None:
            config = ServiceConfig(
                service_type=ServiceType.INFORMATION_EXTRACTION,
                name="信息抽取服务",
                description="从信访内容中抽取街道、区县、详细地址、详细对象等信息",
                version="1.0.0"
            )
        super().__init__(config)
        self.status = ServiceStatus.READY

    # 实现AIService的抽象方法
    async def initialize(self) -> bool:
        """初始化服务"""
        try:
            logger.info(f"初始化信息抽取服务")
            self.status = ServiceStatus.READY
            return True
        except Exception as e:
            logger.error(f"信息抽取服务初始化失败: {str(e)}")
            return False

    def result_to_class(self, result) -> Dict[str, Any]:
        """
        结果转换为结果
        :param result:
        :return:
        """
        new_obj_result = {}
        new_obj_result["dzxx_ds"] = result.get("ds") if result.get("ds") != "无" else ""
        new_obj_result["dzxx_xzq"] = result.get("qx") if result.get("qx") != "无" else ""
        new_obj_result["dzxx_jd"] = result.get("jd") if result.get("jd") != "无" else ""
        new_obj_result["dzxx_tsdz"] = result.get("dz", {}).get("text", "") if result.get("dz", {}).get("text", "无") != "无" else ""
        new_obj_result["dzxx_dz_words"] = result.get("dz", {}).get("words", []) if result.get("dz", {}).get("words",
                                                                                                "无") != "无" else []
        new_obj_result["dzxx_tsdx"] = result.get("dx", {}).get("text", "") if result.get("dx", {}).get("text",
                                                                                                "无") != "无" else ""
        new_obj_result["dzxx_dx_words"] = result.get("dx", {}).get("words", []) if result.get("dx", {}).get("words",
                                                                                                 "无") != "无" else []
        return new_obj_result

    async def process(self, request: ServiceRequest) -> ServiceResponse:
        """处理分析请求"""
        start_time = time.time()
        
        try:
            db = next(get_db())
            # 使用父类的run方法处理请求
            service_class = self._create_service_class(db)
            result = await self.run(service_class, request.data, db)
            # 处理结果
            if result.get("success"):
                extracted_data = self._parse_extracted_result(result.get("response", {}))
                # 添加配置信息到结果
                # extracted_data["config_used"] = analysis_config
                extracted_data["petition_record_id"] = request.data.get("xh", "")
            else:
                extracted_data = {"petition_record_id": request.data.get("xh", "")}

            # 将记录信息和数据进行合并
            all_extracted_data =  request.data|extracted_data

            return ServiceResponse(
                request_id=request.request_id,
                service_type=request.service_type,
                success=result.get("success", False),
                data=all_extracted_data,
                error_message=result.get("error"),
                processing_time=time.time() - start_time
            )
            
        except Exception as e:
            logger.error(f"信息抽取服务处理失败: {str(e)}")
            return ServiceResponse(
                request_id=request.request_id,
                service_type=request.service_type,
                success=False,
                error_message=str(e),
                processing_time=time.time() - start_time
            )
    
    async def health_check(self) -> Dict[str, Any]:
        """健康检查"""
        try:
            return {
                "healthy": True,
                "service_type": "extract_info",
                "service_name": "信息抽取服务",
                "status": "active"
            }
        except Exception as e:
            logger.error(f"信息抽取服务健康检查失败: {str(e)}")
            return {
                "healthy": False,
                "service_type": "extract_info",
                "error": str(e)
            }
    
    def get_capabilities(self) -> Dict[str, Any]:
        """获取服务能力"""
        return {
            "description": "从信访内容中抽取街道、区县、详细地址、详细对象等信息",
            "input_format": {
                "xfnr": "string (信访人)",
                "content": "string (信访内容)"
            },
            "output_format": {
                "street": "string (街道)",
                "district": "string (区县)",
                "address": "string (详细地址)",
                "object": "string (详细对象)"
            },
            "supported_features": [
                "信息抽取",
                "地址解析",
                "结构化输出"
            ]
        }

    def extract_information(self, request_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        执行信息抽取
        
        Args:
            request_data: 请求数据，包含xfnr等字段
        Returns:
            Dict[str, Any]: 抽取结果
        """
        try:
            db = next(get_db())
            # 信息抽取服务没有对应的TaskType，使用通用的配置增强
            # 这里可以扩展为支持信息抽取的特定配置
            enhanced_request = enhance_analysis_request_with_config(
                "information_extraction",  # 使用通用类型
                request_data,
                db
            )

            # 创建服务类对象
            service_class = self._create_service_class(db)
            
            # 如果配置中包含自定义提示词，更新服务类的提示词模板
            analysis_config = enhanced_request.get("analysis_config", {})
            custom_prompt = analysis_config.get("prompt")
            if custom_prompt:
                service_class = self._update_service_prompt(service_class, custom_prompt)

            # 调用父类run方法
            result = self.run(service_class, enhanced_request, db)
            
            # 处理结果
            if result.get("success"):
                extracted_data = self._parse_extracted_result(result.get("response", {}))
                # 添加配置信息到结果
                extracted_data["config_used"] = analysis_config
                return {
                    "success": True,
                    "data": extracted_data,
                    "service_info": {
                        "service_name": self.config.name,
                        "model": service_class.model_code,
                        "provider": service_class.provider,
                        "config_source": "database" if custom_prompt else "default"
                    }
                }
            else:
                return {
                    "success": False,
                    "error": result.get("error", "未知错误")
                }
                
        except Exception as e:
            logger.error(f"信息抽取失败: {str(e)}")
            return {"success": False, "error": str(e)}
    
    def _create_service_class(self, db: Session) -> ServiceClass:
        """创建服务类对象"""
        service_class =  db.query(ServiceClass).filter(
            ServiceClass.service_id == ServiceParamsConfig.INFO_EXTRACTION.service_id).first()
        if service_class:
            return service_class
        config = ServiceParamsConfig.INFO_EXTRACTION

        
        service_class = ServiceClass(
            service_id=config.service_id,
            name=config.name,
            description=config.description,
            provider=config.provider,
            model_code=config.model_name,
            max_tokens=config.max_tokens,
            temperature=config.temperature,
            category="extract_location",
            config=config.config,
            prompt_template_id=ServiceParamsConfig.INFO_EXTRACTION
        )
        
        return service_class


    def _parse_extracted_result(self, response_data: Dict[str, Any]) -> Dict[str, Any]:
        """解析抽取结果"""
        try:
            content = response_data.content
            content = content.strip("\n")
            # 尝试解析JSON
            if content.startswith("{") and content.endswith("}"):
                json_obj = json.loads(content)
                # 整理结果
                json_obj = self.result_to_class(json_obj)
                return json_obj
            else:
                json_obj = json.loads(content)
                self.result_to_class(json_obj)
                # 如果不是JSON，返回原始内容
                return json_obj
            
        except Exception as e:
            logger.error(f"解析抽取结果失败: {str(e)}")
            return {"error": str(e)}

    def _update_service_prompt(self, service_class: ServiceClass, custom_prompt: str) -> ServiceClass:
        """更新服务类的提示词模板"""
        try:
            from core.database import get_db_session

            with get_db_session() as db:
                # 创建自定义提示词模板
                custom_prompt_template = PromptTemplate(
                    name=f"信息抽取自定义提示词_{int(time.time())}",
                    description="用户自定义的信息抽取提示词",
                    content=custom_prompt,
                    template_type="custom",
                    is_active=True
                )

                # 保存自定义模板到数据库
                db.add(custom_prompt_template)
                db.commit()
                db.refresh(custom_prompt_template)

                # 更新服务类的提示词模板ID
                service_class.prompt_template_id = custom_prompt_template.id

                logger.info(f"已更新信息抽取服务提示词模板，模板ID: {custom_prompt_template.id}")
                return service_class

        except Exception as e:
            logger.error(f"更新服务提示词模板失败: {str(e)}")
            # 如果更新失败，返回原服务类
            return service_class



class SpecificationAnalysisService(LLMRunService):
    """规范分析服务 - 基于LLMRunService"""
    
    def __init__(self, config: ServiceConfig = None):
        # 使用规范分析服务配置
        if config is None:
            config = ServiceConfig(
                service_type=ServiceType.COMPLIANCE_CHECK,
                name="规范分析服务",
                description="根据定义判断回复内容是否合规",
                version="1.0.0"
            )
        super().__init__(config)
        # self.initialize()

    # 实现AIService的抽象方法
    async def initialize(self) -> bool:
        """初始化服务"""
        try:
            logger.info(f"初始化规范分析服务")
            self.status = ServiceStatus.READY
            return True
        except Exception as e:
            logger.error(f"规范分析服务初始化失败: {str(e)}")
            return False
    
    async def process(self, request: ServiceRequest) -> ServiceResponse:
        """处理分析请求"""
        start_time = time.time()
        
        try:
            # 建立数据访问对象
            db = next(get_db())
            # 对于不需要识别的逻辑进行处理
            ts_dfnr = request.data.get("ts_dfnr")
            if ts_dfnr is not None:
                # 使用父类的run方法处理请求
                service_class = self._create_service_class(db)
                result = await self.run(service_class, request.data, db)
                # 处理结果
                if result.get("success"):
                    extracted_data = self._parse_analysis_result(result.get("response", {}))
                    # 添加配置信息到结果
                    # extracted_data["config_used"] = analysis_config
                    extracted_data["petition_record_id"] = request.data.get("xh", "")
                    extracted_data["gffx_dfnr"] =request.data.get("ts_dfnr", "")
                else:
                    extracted_data = {"petition_record_id": request.data.get("xh", "")}
                # 将记录信息和数据进行合并
                all_extracted_data = request.data | extracted_data
                return ServiceResponse(
                    request_id=request.request_id,
                    service_type=request.service_type,
                    success=result.get("success", False),
                    data=all_extracted_data,
                    error_message=result.get("error"),
                    processing_time=time.time() - start_time
                )
            else:
                # 对于没有回复内容的不进行解析
                extracted_data = {"petition_record_id": request.data.get("xh", "")}
                extracted_data["gffx_dfnr"] =request.data.get("ts_dfnr", "")
                extracted_data["gffx_zt"] = ""
                extracted_data["gffx_pdly"] = "暂未回复，不进行判断"
                # 将记录信息和数据进行合并
                all_extracted_data = request.data | extracted_data
                return ServiceResponse(
                    request_id=request.request_id,
                    service_type=request.service_type,
                    success=True,
                    data=all_extracted_data,
                    error_message="",
                    processing_time=time.time() - start_time
                )
            
        except Exception as e:
            logger.error(f"规范分析服务处理失败: {str(e)}")
            return ServiceResponse(
                request_id=request.request_id,
                service_type=request.service_type,
                success=False,
                error_message=str(e),
                processing_time=time.time() - start_time
            )
    
    async def health_check(self) -> Dict[str, Any]:
        """健康检查"""
        try:
            return {
                "healthy": True,
                "service_type": "compliance_check",
                "service_name": "规范分析服务",
                "status": "active"
            }
        except Exception as e:
            logger.error(f"规范分析服务健康检查失败: {str(e)}")
            return {
                "healthy": False,
                "service_type": "compliance_check",
                "error": str(e)
            }
    
    def get_capabilities(self) -> Dict[str, Any]:
        """获取服务能力"""
        return {
            "description": "根据定义判断回复内容是否合规",
            "input_format": {
                "dfnr": "string (答复人)",
                "content": "string (答复内容)"
            },
            "output_format": {
                "is_compliant": "boolean (是否合规)",
                "compliance_score": "float (合规分数)",
                "issues": "array (问题列表)",
                "suggestions": "array (建议列表)"
            },
            "supported_features": [
                "规范分析",
                "合规检查",
                "问题识别",
                "改进建议"
            ]
        }
    
    def analyze_compliance(self, request_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        执行规范分析
        
        Args:
            request_data: 请求数据，包含dfnr等字段
            
        Returns:
            Dict[str, Any]: 分析结果
        """
        try:
            db = next(get_db())
            # 使用配置提供器增强请求数据
            enhanced_request = enhance_analysis_request_with_config(
                TaskType.ComplianceAnalysis.value,
                request_data
            )

            # 创建服务类对象
            service_class = self._create_service_class(db)
            
            # 如果配置中包含自定义提示词，更新服务类的提示词模板
            analysis_config = enhanced_request.get("analysis_config", {})
            custom_prompt = analysis_config.get("prompt")
            if custom_prompt:
                service_class = self._update_service_prompt(service_class, custom_prompt)

            # 调用父类run方法
            result = self.run(service_class, enhanced_request, db)
            
            # 处理结果
            if result.get("success"):
                analysis_data = self._parse_analysis_result(result.get("response", {}))
                # 添加配置信息到结果
                analysis_data["config_used"] = analysis_config
                return {
                    "success": True,
                    "data": analysis_data,
                    "service_info": {
                        "service_name": self.config.name,
                        "model": service_class.model_code,
                        "provider": service_class.provider,
                        "config_source": "database" if custom_prompt else "default"
                    }
                }
            else:
                return {
                    "success": False,
                    "error": result.get("error", "未知错误")
                }
                
        except Exception as e:
            logger.error(f"规范分析失败: {str(e)}")
            return {"success": False, "error": str(e)}
    
    def _create_service_class(self, db:Session) -> ServiceClass:
        """创建服务类对象"""
        service_class =  db.query(ServiceClass).filter(
            ServiceClass.service_id == ServiceParamsConfig.SPECIFY_ANALYSIS.service_id).first()
        if service_class:
            return service_class
        config = ServiceParamsConfig.SPECIFY_ANALYSIS
        
        service_class = ServiceClass(
            service_id=config.service_id,
            name=config.name,
            description=config.description,
            provider=config.provider,
            model_code=config.model_name,
            max_tokens=config.max_tokens,
            temperature=config.temperature,
            category="ai_analysis",
            config=config.config,
            prompt_template_id=config.prompt_template_id,
        )
        
        return service_class

    def result_to_class(self, result) -> Dict[str, Any]:
        """
        结果转换为结果
        :param result:
        :return:
        """
        new_obj_result = {}
        if result.get("是否规范") == "无":
            new_obj_result["gffx_zt"] = ""
        elif result.get("是否规范") == "合规":
            new_obj_result["gffx_zt"] = "1"
        else:
            new_obj_result["gffx_zt"] = "0"
        new_obj_result["gffx_pdly"] = result.get("判断依据") if result.get("判断依据") != "无" else ""
        return new_obj_result
    
    def _parse_analysis_result(self, response_data: Dict[str, Any]) -> Dict[str, Any]:
        """解析分析结果"""
        try:
            content = response_data.content
            content = content.strip("\n")
            # 尝试解析JSON
            if content.startswith("{") and content.endswith("}"):
                json_obj = json.loads(content.replace('\n', ""))
                # 整理结果
                json_obj = self.result_to_class(json_obj)
                return json_obj
            else:
                json_obj = json.loads(content.replace('\n', ""))
                json_obj = self.result_to_class(json_obj)
                # 如果不是JSON，返回原始内容
                return json_obj
            
        except Exception as e:
            logger.error(f"解析分析结果失败: {str(e)}")
            return {"error": str(e)}

    def _update_service_prompt(self, service_class: ServiceClass, custom_prompt: str) -> ServiceClass:
        """更新服务类的提示词模板"""
        try:
            from core.database import get_db_session

            with get_db_session() as db:
                # 创建自定义提示词模板
                custom_prompt_template = PromptTemplate(
                    name=f"规范分析自定义提示词_{int(time.time())}",
                    description="用户自定义的规范分析提示词",
                    content=custom_prompt,
                    template_type="custom",
                    is_active=True
                )

                # 保存自定义模板到数据库
                db.add(custom_prompt_template)
                db.commit()
                db.refresh(custom_prompt_template)

                # 更新服务类的提示词模板ID
                service_class.prompt_template_id = custom_prompt_template.id

                logger.info(f"已更新规范分析服务提示词模板，模板ID: {custom_prompt_template.id}")
                return service_class

        except Exception as e:
            logger.error(f"更新服务提示词模板失败: {str(e)}")
            # 如果更新失败，返回原服务类
            return service_class


class SentimentAnalysisService(LLMRunService):
    """情感分析服务 - 基于LLMRunService"""
    
    def __init__(self, config: ServiceConfig = None):
        # 使用情感分析服务配置
        if config is None:
            config = ServiceConfig(
                service_type=ServiceType.SENTIMENT_ANALYSIS,
                name="情感分析服务",
                description="根据定义判断信访内容的情感",
                version="1.0.0"
            )
        super().__init__(config)
        self.config = config
        self.initialize()

    # 实现AIService的抽象方法
    async def initialize(self) -> bool:
        """初始化服务"""
        try:
            logger.info(f"初始化情感分析服务")
            self.status = ServiceStatus.READY
            return True
        except Exception as e:
            logger.error(f"情感分析服务初始化失败: {str(e)}")
            return False
    
    async def process(self, request: ServiceRequest) -> ServiceResponse:
        """处理分析请求"""
        start_time = time.time()
        
        try:
            db = next(get_db())
            # 使用父类的run方法处理请求
            service_class = self._create_service_class(db)
            result = await self.run(service_class, request.data, db)
            # 处理结果
            if result.get("success"):
                extracted_data = self._parse_sentiment_result(result.get("response", {}))
                # 添加配置信息到结果
                # extracted_data["config_used"] = analysis_config
                extracted_data["petition_record_id"] = request.data.get("xh", "")
            else:
                extracted_data = {"petition_record_id": request.data.get("xh", "")}

                # 将记录信息和数据进行合并
            all_extracted_data = request.data | extracted_data
            
            return ServiceResponse(
                request_id=request.request_id,
                service_type=request.service_type,
                success=result.get("success", False),
                data=all_extracted_data,
                error_message=result.get("error"),
                processing_time=time.time() - start_time
            )
            
        except Exception as e:
            logger.error(f"情感分析服务处理失败: {str(e)}")
            return ServiceResponse(
                request_id=request.request_id,
                service_type=request.service_type,
                success=False,
                error_message=str(e),
                processing_time=time.time() - start_time
            )
    
    async def health_check(self) -> Dict[str, Any]:
        """健康检查"""
        try:
            return {
                "healthy": True,
                "service_type": "sentiment_analysis",
                "service_name": "情感分析服务",
                "status": "active"
            }
        except Exception as e:
            logger.error(f"情感分析服务健康检查失败: {str(e)}")
            return {
                "healthy": False,
                "service_type": "sentiment_analysis",
                "error": str(e)
            }
    
    def get_capabilities(self) -> Dict[str, Any]:
        """获取服务能力"""
        return {
            "description": "根据定义判断信访内容的情感",
            "input_format": {
                "xfnr": "string (信访内容)",
            },
            "output_format": {
                "sentiment_level": "string (情感级别: 轻度/中度/重度)",
                "emotion_keywords": "array (情感关键词)",
                "suggestion": "string (判断依据)",
                "confidence_score": "float (置信度分数)"
            },
            "supported_features": [
                "情感分析",
                "情感级别识别",
                "关键词提取",
                "处理建议生成"
            ]
        }
    
    def analyze_sentiment(self, request_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        执行情感分析
        
        Args:
            request_data: 请求数据，包含xfnr等字段
            
        Returns:
            Dict[str, Any]: 分析结果
        """
        try:
            db = next(get_db())
            # 使用配置提供器增强请求数据
            enhanced_request = enhance_analysis_request_with_config(
                TaskType.SentimentAnalysis.value,
                request_data
            )

            # 创建服务类对象
            service_class = self._create_service_class(db)
            
            # 如果配置中包含自定义提示词，更新服务类的提示词模板
            analysis_config = enhanced_request.get("analysis_config", {})
            custom_prompt = analysis_config.get("prompt")
            if custom_prompt:
                service_class = self._update_service_prompt(service_class, custom_prompt)

            # 调用父类run方法
            result = self.run(service_class, enhanced_request, db)
            
            # 处理结果
            if result.get("success"):
                sentiment_data = self._parse_sentiment_result(result.get("response", {}))
                # 添加配置信息到结果
                sentiment_data["config_used"] = analysis_config
                return {
                    "success": True,
                    "data": sentiment_data,
                    "service_info": {
                        "service_name": self.config.name,
                        "model": service_class.model_code,
                        "provider": service_class.provider,
                        "config_source": "database" if custom_prompt else "default"
                    }
                }
            else:
                return {
                    "success": False,
                    "error": result.get("error", "未知错误")
                }
                
        except Exception as e:
            logger.error(f"情感分析失败: {str(e)}")
            return {"success": False, "error": str(e)}
    
    def _create_service_class(self, db: Session) -> ServiceClass:
        """创建服务类对象"""
        service_class =  db.query(ServiceClass).filter(
            ServiceClass.service_id == ServiceParamsConfig.SENTIMENT_ANALYSIS.service_id).first()
        if service_class:
            return service_class
        config = ServiceParamsConfig.SENTIMENT_ANALYSIS
        
        service_class = ServiceClass(
            service_id=config.service_id,
            name=config.name,
            description=config.description,
            provider=config.provider,
            model_code=config.model_name,
            max_tokens=config.max_tokens,
            temperature=config.temperature,
            category="ai_analysis",
            config=config.config,
            prompt_template_id = config.prompt_template_id,
        )
        
        return service_class

    def result_to_class(self, result) -> Dict[str, Any]:
        """
        结果转换为结果
        :param result:
        :return:
        """
        new_obj_result = {}
        new_obj_result["qgfx_lx"] = result.get("情感类型") if result.get("情感类型") != "无" else ""
        new_obj_result["qgfx_pdly"] = result.get("判断理由") if result.get("判断理由") != "无" else ""
        new_obj_result["qgfx_zy"] = result.get("摘要") if result.get("摘要") != "无" else ""
        new_obj_result["qgfx_gjc"] = result.get("关键词") if result.get("关键词") != "无" else ""
        return new_obj_result

    def _parse_sentiment_result(self, response_data: Dict[str, Any]) -> Dict[str, Any]:
        """解析情感分析结果"""
        try:
            content = response_data.content
            content = content.strip("\n")
            # 尝试解析JSON
            if content.startswith("{") and content.endswith("}"):
                json_obj = json.loads(content)
                # 整理结果
                json_obj = self.result_to_class(json_obj)
                return json_obj
            else:
                json_obj = json.loads(content)
                self.result_to_class(json_obj)
                # 如果不是JSON，返回原始内容
                return json_obj
            
        except Exception as e:
            logger.error(f"解析情感分析结果失败: {str(e)}")
            return {"error": str(e)}

    def _update_service_prompt(self, service_class: ServiceClass, custom_prompt: str) -> ServiceClass:
        """更新服务类的提示词模板"""
        try:
            from core.database import get_db_session

            with get_db_session() as db:
                # 创建自定义提示词模板
                custom_prompt_template = PromptTemplate(
                    name=f"情感分析自定义提示词_{int(time.time())}",
                    description="用户自定义的情感分析提示词",
                    content=custom_prompt,
                    template_type="custom",
                    is_active=True
                )

                # 保存自定义模板到数据库
                db.add(custom_prompt_template)
                db.commit()
                db.refresh(custom_prompt_template)

                # 更新服务类的提示词模板ID
                service_class.prompt_template_id = custom_prompt_template.id

                logger.info(f"已更新情感分析服务提示词模板，模板ID: {custom_prompt_template.id}")
                return service_class

        except Exception as e:
            logger.error(f"更新服务提示词模板失败: {str(e)}")
            # 如果更新失败，返回原服务类
            return service_class


class RegionalAnalysisService(LLMRunService):
    """区域分析服务 - 基于LLMRunService"""

    def __init__(self, config: ServiceConfig = None):
        # 使用区域分析服务配置
        if config is None:
            config = ServiceConfig(
                service_type="regional_analysis",
                name="区域分析服务",
                description="分析信访内容的地域分布特征",
                version="1.0.0",
                max_concurrent_requests=5,
                timeout=60
            )
        super().__init__(config)

    # 实现AIService的抽象方法
    async def initialize(self) -> bool:
        """初始化服务"""
        try:
            logger.info(f"初始化区域分析服务")
            return True
        except Exception as e:
            logger.error(f"区域分析服务初始化失败: {str(e)}")
            return False

    async def process(self, request: ServiceRequest) -> ServiceResponse:
        """处理分析请求"""
        start_time = time.time()

        try:
            # 使用父类的run方法处理请求
            service_class = self._create_service_class()
            result = self.run(service_class, request.data)

            return ServiceResponse(
                request_id=request.request_id,
                service_type=request.service_type,
                success=result.get("success", False),
                data=result.get("data", {}),
                error_message=result.get("error"),
                processing_time=time.time() - start_time
            )

        except Exception as e:
            logger.error(f"区域分析服务处理失败: {str(e)}")
            return ServiceResponse(
                request_id=request.request_id,
                service_type=request.service_type,
                success=False,
                error_message=str(e),
                processing_time=time.time() - start_time
            )

    async def health_check(self) -> Dict[str, Any]:
        """健康检查"""
        try:
            return {
                "healthy": True,
                "service_type": "regional_analysis",
                "service_name": "区域分析服务",
                "status": "active"
            }
        except Exception as e:
            logger.error(f"区域分析服务健康检查失败: {str(e)}")
            return {
                "healthy": False,
                "service_type": "regional_analysis",
                "error": str(e)
            }

    def get_capabilities(self) -> Dict[str, Any]:
        """获取服务能力"""
        return {
            "description": "分析信访内容的地域分布特征",
            "input_format": {
                "petition_data": "array (信访数据数组)",
                "analysis_levels": "array (分析层级，如: ['地市', '区县'])",
                "region_codes": "string (行政区划代码)"
            },
            "output_format": {
                "regional_distribution": "object (地域分布数据)",
                "hotspot_regions": "array (热点区域)",
                "trend_analysis": "object (趋势分析)"
            },
            "supported_features": [
                "区域分析",
                "热点识别",
                "趋势分析",
                "可视化数据"
            ]
        }

    def analyze_regional(self, request_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        执行区域分析

        Args:
            request_data: 请求数据，包含petition_data等字段

        Returns:
            Dict[str, Any]: 分析结果
        """
        try:
            # 使用配置提供器增强请求数据
            enhanced_request = enhance_analysis_request_with_config(
                TaskType.RegionalAnalysis.value,
                request_data
            )

            # 创建服务类对象
            service_class = self._create_service_class()

            # 如果配置中包含自定义参数，更新服务配置
            analysis_config = enhanced_request.get("analysis_config", {})
            custom_prompt = analysis_config.get("prompt")
            analysis_levels = analysis_config.get("analysis_levels", ["地市", "区县"])
            region_codes = analysis_config.get("region_codes", "")

            if custom_prompt:
                service_class = self._update_service_prompt(service_class, custom_prompt)

            # 添加区域分析特定配置到请求数据
            enhanced_request["analysis_levels"] = analysis_levels
            enhanced_request["region_codes"] = region_codes

            # 调用父类run方法
            result = self.run(service_class, enhanced_request)

            # 处理结果
            if result.get("success"):
                regional_data = self._parse_regional_result(result.get("response", {}))
                # 添加配置信息到结果
                regional_data["config_used"] = {
                    "prompt": custom_prompt,
                    "analysis_levels": analysis_levels,
                    "region_codes": region_codes
                }
                return {
                    "success": True,
                    "data": regional_data,
                    "service_info": {
                        "service_name": self.config.name,
                        "model": service_class.model_code,
                        "provider": service_class.provider,
                        "config_source": "database" if custom_prompt else "default"
                    }
                }
            else:
                return {
                    "success": False,
                    "error": result.get("error", "未知错误")
                }

        except Exception as e:
            logger.error(f"区域分析失败: {str(e)}")
            return {"success": False, "error": str(e)}

    def _create_service_class(self) -> ServiceClass:
        """创建服务类对象"""
        # 区域分析服务没有预定义的ServiceConfig，创建自定义配置
        service_class = ServiceClass(
            service_id="regional_analysis_service",
            name="区域分析服务",
            description="分析信访内容的地域分布特征",
            provider="zhipu",
            model_code="glm-4-flash",
            max_tokens=2000,
            temperature=0.3,
            category="regional_analysis",
            config={}
        )

        return service_class

    def _parse_regional_result(self, response_data: Dict[str, Any]) -> Dict[str, Any]:
        """解析区域分析结果"""
        try:
            content = response_data.get("content", "")

            # 尝试解析JSON
            if content.startswith("{") and content.endswith("}"):
                import json
                return json.loads(content)

            # 如果不是JSON，返回原始内容
            return {"raw_content": content}

        except Exception as e:
            logger.error(f"解析区域分析结果失败: {str(e)}")
            return {"error": str(e)}

    def _update_service_prompt(self, service_class: ServiceClass, custom_prompt: str) -> ServiceClass:
        """更新服务类的提示词模板"""
        try:
            from core.database import get_db_session

            with get_db_session() as db:
                # 创建自定义提示词模板
                custom_prompt_template = PromptTemplate(
                    name=f"区域分析自定义提示词_{int(time.time())}",
                    description="用户自定义的区域分析提示词",
                    content=custom_prompt,
                    template_type="custom",
                    is_active=True
                )

                # 保存自定义模板到数据库
                db.add(custom_prompt_template)
                db.commit()
                db.refresh(custom_prompt_template)

                # 更新服务类的提示词模板ID
                service_class.prompt_template_id = custom_prompt_template.id

                logger.info(f"已更新区域分析服务提示词模板，模板ID: {custom_prompt_template.id}")
                return service_class

        except Exception as e:
            logger.error(f"更新服务提示词模板失败: {str(e)}")
            # 如果更新失败，返回原服务类
            return service_class


class ComplaintTypeAnalysisService(LLMRunService):
    """投诉类型分析服务 - 基于LLMRunService"""

    def __init__(self, config: ServiceConfig = None):
        # 使用投诉类型分析服务配置
        if config is None:
            config = ServiceConfig(
                service_type="complaint_type_analysis",
                name="投诉类型分析服务",
                description="分析信访内容的投诉类型分类",
                version="1.0.0",
                max_concurrent_requests=5,
                timeout=45
            )
        super().__init__(config)

    # 实现AIService的抽象方法
    async def initialize(self) -> bool:
        """初始化服务"""
        try:
            logger.info(f"初始化投诉类型分析服务")
            return True
        except Exception as e:
            logger.error(f"投诉类型分析服务初始化失败: {str(e)}")
            return False

    async def process(self, request: ServiceRequest) -> ServiceResponse:
        """处理分析请求"""
        start_time = time.time()

        try:
            # 使用父类的run方法处理请求
            service_class = self._create_service_class()
            result = self.run(service_class, request.data)

            return ServiceResponse(
                request_id=request.request_id,
                service_type=request.service_type,
                success=result.get("success", False),
                data=result.get("data", {}),
                error_message=result.get("error"),
                processing_time=time.time() - start_time
            )

        except Exception as e:
            logger.error(f"投诉类型分析服务处理失败: {str(e)}")
            return ServiceResponse(
                request_id=request.request_id,
                service_type=request.service_type,
                success=False,
                error_message=str(e),
                processing_time=time.time() - start_time
            )

    async def health_check(self) -> Dict[str, Any]:
        """健康检查"""
        try:
            return {
                "healthy": True,
                "service_type": "complaint_type_analysis",
                "service_name": "投诉类型分析服务",
                "status": "active"
            }
        except Exception as e:
            logger.error(f"投诉类型分析服务健康检查失败: {str(e)}")
            return {
                "healthy": False,
                "service_type": "complaint_type_analysis",
                "error": str(e)
            }

    def get_capabilities(self) -> Dict[str, Any]:
        """获取服务能力"""
        return {
            "description": "分析信访内容的投诉类型分类",
            "input_format": {
                "petition_content": "string (信访内容)",
                "petition_context": "object (信访上下文信息，可选)"
            },
            "output_format": {
                "complaint_types": "array (投诉类型分类)",
                "primary_type": "string (主要投诉类型)",
                "secondary_types": "array (次要投诉类型)",
                "confidence_score": "float (置信度分数)",
                "classification_reason": "string (分类依据)"
            },
            "supported_features": [
                "投诉类型分类",
                "多级分类",
                "置信度评分",
                "分类依据生成"
            ]
        }

    def analyze_complaint_type(self, request_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        执行投诉类型分析

        Args:
            request_data: 请求数据，包含petition_content等字段

        Returns:
            Dict[str, Any]: 分析结果
        """
        try:
            # 使用配置提供器增强请求数据
            enhanced_request = enhance_analysis_request_with_config(
                TaskType.ComplaintTypeAnalysis.value,
                request_data
            )

            # 创建服务类对象
            service_class = self._create_service_class()

            # 如果配置中包含自定义提示词，更新服务类的提示词模板
            analysis_config = enhanced_request.get("analysis_config", {})
            custom_prompt = analysis_config.get("prompt")
            if custom_prompt:
                service_class = self._update_service_prompt(service_class, custom_prompt)

            # 调用父类run方法
            result = self.run(service_class, enhanced_request)

            # 处理结果
            if result.get("success"):
                complaint_type_data = self._parse_complaint_type_result(result.get("response", {}))
                # 添加配置信息到结果
                complaint_type_data["config_used"] = analysis_config
                return {
                    "success": True,
                    "data": complaint_type_data,
                    "service_info": {
                        "service_name": self.config.name,
                        "model": service_class.model_code,
                        "provider": service_class.provider,
                        "config_source": "database" if custom_prompt else "default"
                    }
                }
            else:
                return {
                    "success": False,
                    "error": result.get("error", "未知错误")
                }

        except Exception as e:
            logger.error(f"投诉类型分析失败: {str(e)}")
            return {"success": False, "error": str(e)}

    def _create_service_class(self) -> ServiceClass:
        """创建服务类对象"""
        # 投诉类型分析服务没有预定义的ServiceConfig，创建自定义配置
        service_class = ServiceClass(
            service_id="complaint_type_analysis_service",
            name="投诉类型分析服务",
            description="分析信访内容的投诉类型分类",
            provider="zhipu",
            model_code="glm-4-flash",
            max_tokens=2000,
            temperature=0.3,
            category="complaint_type_analysis",
            config={}
        )

        return service_class

    def _parse_complaint_type_result(self, response_data: Dict[str, Any]) -> Dict[str, Any]:
        """解析投诉类型分析结果"""
        try:
            content = response_data.get("content", "")

            # 尝试解析JSON
            if content.startswith("{") and content.endswith("}"):
                import json
                return json.loads(content)

            # 如果不是JSON，返回原始内容
            return {"raw_content": content}

        except Exception as e:
            logger.error(f"解析投诉类型分析结果失败: {str(e)}")
            return {"error": str(e)}

    def _update_service_prompt(self, service_class: ServiceClass, custom_prompt: str) -> ServiceClass:
        """更新服务类的提示词模板"""
        try:
            from core.database import get_db_session

            with get_db_session() as db:
                # 创建自定义提示词模板
                custom_prompt_template = PromptTemplate(
                    name=f"投诉类型分析自定义提示词_{int(time.time())}",
                    description="用户自定义的投诉类型分析提示词",
                    content=custom_prompt,
                    template_type="custom",
                    is_active=True
                )

                # 保存自定义模板到数据库
                db.add(custom_prompt_template)
                db.commit()
                db.refresh(custom_prompt_template)

                # 更新服务类的提示词模板ID
                service_class.prompt_template_id = custom_prompt_template.id

                logger.info(f"已更新投诉类型分析服务提示词模板，模板ID: {custom_prompt_template.id}")
                return service_class

        except Exception as e:
            logger.error(f"更新服务提示词模板失败: {str(e)}")
            # 如果更新失败，返回原服务类
            return service_class


class DuplicateAnalysisService(LLMRunService):
    """重复分析服务 - 基于LLMRunService"""

    def __init__(self, config: ServiceConfig = None):
        # 使用重复分析服务配置
        if config is None:
            config = ServiceConfig(
                service_type="duplicate_analysis",
                name="重复分析服务",
                description="识别重复或相似的信访内容",
                version="1.0.0",
                max_concurrent_requests=3,
                timeout=90
            )
        super().__init__(config)

    # 实现AIService的抽象方法
    async def initialize(self) -> bool:
        """初始化服务"""
        try:
            logger.info(f"初始化重复分析服务")
            return True
        except Exception as e:
            logger.error(f"重复分析服务初始化失败: {str(e)}")
            return False

    async def process(self, request: ServiceRequest) -> ServiceResponse:
        """处理分析请求"""
        start_time = time.time()

        try:
            # 使用父类的run方法处理请求
            service_class = self._create_service_class()
            result = self.run(service_class, request.data)

            return ServiceResponse(
                request_id=request.request_id,
                service_type=request.service_type,
                success=result.get("success", False),
                data=result.get("data", {}),
                error_message=result.get("error"),
                processing_time=time.time() - start_time
            )

        except Exception as e:
            logger.error(f"重复分析服务处理失败: {str(e)}")
            return ServiceResponse(
                request_id=request.request_id,
                service_type=request.service_type,
                success=False,
                error_message=str(e),
                processing_time=time.time() - start_time
            )

    async def health_check(self) -> Dict[str, Any]:
        """健康检查"""
        try:
            return {
                "healthy": True,
                "service_type": "duplicate_analysis",
                "service_name": "重复分析服务",
                "status": "active"
            }
        except Exception as e:
            logger.error(f"重复分析服务健康检查失败: {str(e)}")
            return {
                "healthy": False,
                "service_type": "duplicate_analysis",
                "error": str(e)
            }

    def get_capabilities(self) -> Dict[str, Any]:
        """获取服务能力"""
        return {
            "description": "识别重复或相似的信访内容",
            "input_format": {
                "target_petition": "object (目标信访记录)",
                "comparison_petitions": "array (对比信访记录数组)",
                "filter_words": "array (过滤关键词数组)"
            },
            "output_format": {
                "is_duplicate": "boolean (是否为重复信访)",
                "similarity_score": "float (相似度分数)",
                "duplicate_type": "string (重复类型)",
                "matched_keywords": "array (匹配的关键词)",
                "analysis_reason": "string (分析依据)"
            },
            "supported_features": [
                "重复识别",
                "相似度计算",
                "关键词过滤",
                "重复类型分类"
            ]
        }

    def analyze_duplicates(self, request_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        执行重复分析

        Args:
            request_data: 请求数据，包含target_petition等字段

        Returns:
            Dict[str, Any]: 分析结果
        """
        try:
            # 使用配置提供器增强请求数据
            enhanced_request = enhance_analysis_request_with_config(
                TaskType.DuplicateAnalysis.value,
                request_data
            )

            # 创建服务类对象
            service_class = self._create_service_class()

            # 如果配置中包含自定义参数，更新服务配置
            analysis_config = enhanced_request.get("analysis_config", {})
            custom_prompt = analysis_config.get("prompt")
            filter_words = analysis_config.get("filter_words", ["重复", "再次", "又"])

            if custom_prompt:
                service_class = self._update_service_prompt(service_class, custom_prompt)

            # 添加重复分析特定配置到请求数据
            enhanced_request["filter_words"] = filter_words

            # 调用父类run方法
            result = self.run(service_class, enhanced_request)

            # 处理结果
            if result.get("success"):
                duplicate_data = self._parse_duplicate_result(result.get("response", {}))
                # 添加配置信息到结果
                duplicate_data["config_used"] = {
                    "prompt": custom_prompt,
                    "filter_words": filter_words
                }
                return {
                    "success": True,
                    "data": duplicate_data,
                    "service_info": {
                        "service_name": self.config.name,
                        "model": service_class.model_code,
                        "provider": service_class.provider,
                        "config_source": "database" if custom_prompt else "default"
                    }
                }
            else:
                return {
                    "success": False,
                    "error": result.get("error", "未知错误")
                }

        except Exception as e:
            logger.error(f"重复分析失败: {str(e)}")
            return {"success": False, "error": str(e)}

    def _create_service_class(self) -> ServiceClass:
        """创建服务类对象"""
        # 重复分析服务没有预定义的ServiceConfig，创建自定义配置
        service_class = ServiceClass(
            service_id="duplicate_analysis_service",
            name="重复分析服务",
            description="识别重复或相似的信访内容",
            provider="zhipu",
            model_code="glm-4-flash",
            max_tokens=2000,
            temperature=0.3,
            category="duplicate_analysis",
            config={}
        )

        return service_class

    def _parse_duplicate_result(self, response_data: Dict[str, Any]) -> Dict[str, Any]:
        """解析重复分析结果"""
        try:
            content = response_data.get("content", "")

            # 尝试解析JSON
            if content.startswith("{") and content.endswith("}"):
                import json
                return json.loads(content)

            # 如果不是JSON，返回原始内容
            return {"raw_content": content}

        except Exception as e:
            logger.error(f"解析重复分析结果失败: {str(e)}")
            return {"error": str(e)}

    def _update_service_prompt(self, service_class: ServiceClass, custom_prompt: str) -> ServiceClass:
        """更新服务类的提示词模板"""
        try:
            from core.database import get_db_session

            with get_db_session() as db:
                # 创建自定义提示词模板
                custom_prompt_template = PromptTemplate(
                    name=f"重复分析自定义提示词_{int(time.time())}",
                    description="用户自定义的重复分析提示词",
                    content=custom_prompt,
                    template_type="custom",
                    is_active=True
                )

                # 保存自定义模板到数据库
                db.add(custom_prompt_template)
                db.commit()
                db.refresh(custom_prompt_template)

                # 更新服务类的提示词模板ID
                service_class.prompt_template_id = custom_prompt_template.id

                logger.info(f"已更新重复分析服务提示词模板，模板ID: {custom_prompt_template.id}")
                return service_class

        except Exception as e:
            logger.error(f"更新服务提示词模板失败: {str(e)}")
            # 如果更新失败，返回原服务类
            return service_class



